<?php

namespace App\Http\Controllers;

use DB;
use Illuminate\Http\Request;
use Validator;

class UserTeamController extends Controller
{
    public function index(Request $request, $userId){
        $input = $request->all();
        //参数检验
        $validator = Validator::make($input,
            [
                'search'  => 'string|min:1',
            ]
        );
        if($validator->fails())
            return $this::jsonResponse(true,$validator->messages(),"paramError");
        
        $search     = isset($input["search"])?$input["search"]:"";
      
        $teamResult = DB::table("tm_team")
            ->select("tm_team.id","tm_team.name","tm_team.description","tm_team.icon","tm_team.user_count","tm_team.leader_id","tm_team.is_verified",
                "tm_team.created_at","tm_team.is_public",
                "tm_team_user.is_stick","tm_team_user.join_time")
            ->join("tm_team_user","tm_team_user.team_id","=","tm_team.id")
            ->where("tm_team.is_deleted",false)
            ->where("tm_team.name","like","%$search%")
            ->where("tm_team_user.state",1)
            ->where("tm_team_user.is_deleted",false)
            ->where("tm_team_user.user_id",$userId)
            ->orderBy("tm_team_user.is_stick","Desc")
            ->orderBy("tm_team_user.join_time","Desc")->get();
        
        foreach ($teamResult as $key => $value) {
            if($value->leader_id == $userId){
                $value->is_leader = true;
            }else{
                $value->is_leader = false;  
            }
        }
        return $this->jsonResponse(false,$teamResult);
    }

    public function stickStore($userId,$teamId){
        $teamUserUpdateResult = DB::table("tm_team_user")
            ->where("user_id",$userId)
            ->where("team_id",$teamId)
            ->where("is_deleted",false)
            ->where("state",1)
            ->update(["is_stick"=>true]);

        return $this->jsonResponse(false,$teamUserUpdateResult);
    }

    public function stickDestroy($userId,$teamId){
        $teamUserUpdateResult = DB::table("tm_team_user")
            ->where("user_id",$userId)
            ->where("team_id",$teamId)
            ->where("is_deleted",false)
            ->where("state",1)
            ->update(["is_stick"=>false]);

        return $this->jsonResponse(false,$teamUserUpdateResult);
    }

}